package com.deer.wms.base.system.web.zhBusiness.business;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.deer.wms.base.system.model.task.TaskInfoDto;
import com.deer.wms.base.system.model.ware.ShelfInfo;
import com.deer.wms.base.system.model.zh.CacheLine;
import com.deer.wms.base.system.model.zh.ShelfPlan;
import com.deer.wms.base.system.model.zh.ZhResult;
import com.deer.wms.base.system.service.ware.ICellInfoService;
import com.deer.wms.base.system.service.ware.IShelfInfoService;
import com.deer.wms.base.system.service.zh.ShelfPlanService;
import com.deer.wms.base.system.service.zh.ZhMesService;
import com.deer.wms.base.system.util.JedisServiceUtil;
import com.deer.wms.common.core.controller.BaseController;
import com.deer.wms.common.core.domain.AjaxResult;
import com.deer.wms.common.core.page.TableDataInfo;
import com.deer.wms.common.core.result.CommonCode;
import com.deer.wms.common.core.result.Result;
import com.deer.wms.common.core.result.ResultGenerator;
import com.deer.wms.framework.util.ShiroUtils;
import com.deer.wms.system.domain.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 李帅辰
 * @date 2021/5/26 14:54
 */
@Controller
@RequestMapping("/ShelfPlan")
public class ShelfPlanConreoller  extends BaseController {

    @Autowired
    private ShelfPlanService shelfPlanService;

    @Autowired
    private ICellInfoService cellInfoService;

    @Autowired
    private IShelfInfoService shelfInfoService;

    @Autowired
    private JedisServiceUtil jedisServiceUtil;

    @Autowired
    private ZhMesService zhMesService;

    private String prefix = "shelfPlan";

    /**
     *跳转显示页面
     * @return
     */
    @RequiresPermissions("ShelfPlan:view")
    @GetMapping
    public String ShelfPlan()
    {
        return prefix + "/ShelfPlan";
    }

    @RequiresPermissions("ShelfPlan:findList")
    @PostMapping("/findList")
    @ResponseBody
    public TableDataInfo findList(ShelfPlan shelfPlan) {
        startPage();
        List<ShelfPlan> list = shelfPlanService.findShelfPlanList(shelfPlan);
        return getDataTable(list);
    }

    /**
     * 新增跳转页面
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    @RequiresPermissions("ShelfPlan:add")
    @PostMapping("/insert")
    @ResponseBody
    @Transactional
    public Result insert(ShelfPlan shelfPlan) throws Exception {
        String createUserName = ShiroUtils.getLoginName();

        ShelfPlan shelfPlan1 = new ShelfPlan();

        shelfPlan1.setShelfId( shelfPlan.getShelfId());
        //判断此缓存线是否重复设置信息
        ShelfPlan shelfPlan2 = new ShelfPlan();
        shelfPlan2.setShelfId(shelfPlan.getShelfId());
        ShelfPlan shelfPlanById = shelfPlanService.findShelfPlanByshelfPlan(shelfPlan2);
        if (null!=shelfPlanById){
            return ResultGenerator.genFailResult(CommonCode.SHELFPLAN_ERROR, "false");
        }
        shelfPlan.setCreateUserName(createUserName);
        int i = shelfPlanService.saveShelfPlan(shelfPlan);
        if (i!=0){
            ShelfInfo shelfInfo = shelfInfoService.selectShelfInfoById(shelfPlan.getShelfId());
            //缓存线状态发生变化时，需要在此处同步MES
            CacheLine cacheLine = new CacheLine();
            cacheLine.setStockId(shelfInfo.getShelfCode());
            if (shelfPlan.getState()==-1){
                cacheLine.setState("NG");
            }else {
                cacheLine.setState("OK");
            }
            cacheLine.setDescription(shelfPlan.getDescription());
            String s = zhMesService.CacheLineMes(cacheLine);
            logger.info(createUserName+",修改了缓存线,"+cacheLine.toString()+"MES返回值"+s);


            //  List<ZhResult>  zhResults = JSONObject.parseArray(s, ZhResult.class);
            ZhResult zhResult= JSONArray.parseObject(s, ZhResult.class);//获取到当前执行中的任务
            // for (ZhResult zhResult : zhResults) {
            String msg = zhResult.getMsg();
            String date = zhResult.getDate();
            Integer code = zhResult.getCode();
            ShelfPlan shelfPlan3 = new ShelfPlan();
            shelfPlan3.setMesResult("响应结果："+msg+",响应时间"+date);
            ShelfInfo shelfInfoByshelfCode = shelfInfoService.findShelfInfoByshelfCode(cacheLine.getStockId());
            shelfPlan3.setShelfId(shelfInfoByshelfCode.getShelfId());
            shelfPlanService.updateShelfPlan(shelfPlan3);
            if (code!=0){
                return ResultGenerator.genFailResult(CommonCode.MES_ERROR, "false");
            }
            return  ResultGenerator.genSuccessResult();
        }

        return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR, "false");
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @RequiresPermissions("ShelfPlan:remove")
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids){
        return toAjax(shelfPlanService.delectShelfPlanByIds(ids));
    }


    /**
     * 修改跳转页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        ShelfPlan shelfPlan = shelfPlanService.findShelfPlanById(id);
        mmap.put("shelfPlan", shelfPlan);
        return prefix+"/edit";
    }

    @Transactional
    @RequiresPermissions("ShelfPlan:edit")
    @PostMapping("/edit")
    @ResponseBody
    public Result editSave(ShelfPlan shelfPlan) throws Exception {
        String createUserName = ShiroUtils.getLoginName();
        ShelfPlan shelfPlanById = shelfPlanService.findShelfPlanById(shelfPlan.getId());
        if (null == shelfPlanById){
            return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR, "false");
        }
        if (!(shelfPlan.getState().equals(shelfPlanById.getState()))){
            //缓存线状态发生变化时，需要在此处同步MES
            CacheLine cacheLine = new CacheLine();
            cacheLine.setStockId(shelfPlanById.getShelfCode());
            if (shelfPlan.getState()==-1){
                cacheLine.setState("NG");
            }else {
                cacheLine.setState("OK");
            }
            cacheLine.setDescription(shelfPlan.getDescription());
            String s = zhMesService.CacheLineMes(cacheLine);//mes发送HTTP请求
            logger.info(createUserName+",修改了缓存线,"+cacheLine.toString()+"MES返回值"+s);


           //  List<ZhResult>  zhResults = JSONObject.parseArray(s, ZhResult.class);
            ZhResult zhResult= JSONArray.parseObject(s, ZhResult.class);//mes的返回值
               // for (ZhResult zhResult : zhResults) {
                    String msg = zhResult.getMsg();
                    String date = zhResult.getDate();
                    Integer code = zhResult.getCode();
                    ShelfPlan shelfPlan1 = new ShelfPlan();
                    shelfPlan1.setMesResult("响应结果："+msg+",响应时间"+date);
                    ShelfInfo shelfInfoByshelfCode = shelfInfoService.findShelfInfoByshelfCode(cacheLine.getStockId());
                    shelfPlan1.setShelfId(shelfInfoByshelfCode.getShelfId());
                    shelfPlanService.updateShelfPlan(shelfPlan1);
                    if (code!=0){
                        return ResultGenerator.genFailResult(CommonCode.MES_ERROR, "false");
                    }
               // }
        }

        if (shelfPlan.getState()==shelfPlanById.getState()) {
            if (cellInfoService.getCellInfoCountByShelf(shelfPlan.getShelfId()) != 0) {
                return ResultGenerator.genFailResult(CommonCode.CELLINFO_EDITERROR, "false");
            }
        }
        shelfPlan.setUpdateUserName(createUserName);
        int i = shelfPlanService.updateShelfPlan(shelfPlan);
        if (i!=0){
            return  ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR, "false");
    }

}
